<template>
  <div id="public1">
    <!--订单查询统计-->
    <div class="all-order">
      <span>
        <i class="el-icon-document-checked"></i>
        总订单数：{{allOrder.totalNum}}
      </span>
      <span>
        <i class="el-icon-bank-card"></i>
        总金额：{{allOrder.totalMoney}}
      </span>
      <span>
        <i class="el-icon-document-delete"></i>
        总退款金额：{{allOrder.totalRefund}}
      </span>
    </div>
    <!--搜索-->
    <div class="search-content">
      <el-input v-model="name" placeholder="请输入用户昵称查询" prefix-icon="el-icon-search" clearable @change="inquiryList"/>
      <el-input v-model="agentName" placeholder="请输入代理名称查询" prefix-icon="el-icon-search" clearable
                @change="inquiryList"/>
      <el-input v-model="order" placeholder="请输入系统订单号查询" prefix-icon="el-icon-search" clearable @change="inquiryList"/>
      <el-input v-model="paypalOrder" placeholder="请输入paypal订单号查询" prefix-icon="el-icon-search" clearable @change="inquiryList"/>
      <el-select v-model="status" clearable placeholder="请选择订单状态" @change="inquiryList">
        <el-option
          v-for="item in statusList"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
      <el-date-picker
        v-model="dateTimeRange"
        type="datetimerange"
        range-separator="至"
        clearable
        value-format="yyyy-MM-dd HH:mm:ss"
        @change="inquiryList"
        :picker-options="pickerOptions"
        start-placeholder="开始日期"
        end-placeholder="结束日期">
      </el-date-picker>
      <el-button type="primary" icon="el-icon-search" @click="inquiryList">查询</el-button>
    </div>
    <!--操作列表-->
    <div class="table">
      <el-table fit :data="tableData" style="width: 100%">
        <el-table-column label="用户昵称" prop="member" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.member">{{scope.row.member.name}}</span>
            <span v-else>无</span>
          </template>
        </el-table-column>
        <el-table-column label="代理名称" prop="agent" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.agent">{{scope.row.agent.name}}</span>
            <span v-else>无</span>
          </template>
        </el-table-column>
        <el-table-column label="系统订单号" prop="sn" width="170" align="center"/>
        <el-table-column label="paypal订单号" prop="paypalSn" width="170" align="center"/>
        <el-table-column label="创建时间" prop="createDate" width="170" align="center"/>
        <el-table-column label="支付时间" prop="successTime" width="170" align="center"/>
        <el-table-column label="已退款" prop="refundMoney"  align="center">
          <template slot-scope="scope">
            <el-tag size="small" type="danger" >{{scope.row.refundMoney}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="订单金额" prop="money" align="center"/>
        <!--<el-table-column label="充值备注" prop="remarks" width="300" align="center">-->
          <!--<template slot-scope="scope">-->
            <!--<span v-if="scope.row.remarks==null||scope.row.remarks.length<20">{{scope.row.remarks}}</span>-->

            <!--<el-tooltip v-else :content="scope.row.remarks" placement="top">-->
              <!--<span>{{scope.row.remarks.substring(0,19)+"..."}}</span>-->
            <!--</el-tooltip>-->
          <!--</template>-->
        <!--</el-table-column>-->
        <el-table-column label="操作" width="200" align="center">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="dealwithView(scope.$index, scope.row)">订单详情</el-button>
            <el-button size="mini" type="danger" :disabled="scope.row.status!=='success'" @click="dealwithRefund(scope.$index, scope.row)">退款</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页-->
      <div class="pagination">
        <el-pagination
          :current-page.sync="currentPage"
          :page-sizes="[10,20,30,40,50]"
          layout="total,sizes, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!--订单退款蒙层-->
    <el-dialog id="refund-dialog" title="订单退款" :visible.sync="refundDialogVisible">
      <el-form label-position="right" label-width="30%"  :model="refund"  :rules="refundRules" ref="refundRuleForm">
        <el-form-item label="退款金额：" prop="money">
          <el-input v-model="refund.money" placeholder="请输入退款金额" clearable />
        </el-form-item>
        <el-form-item label="退款说明：">
          <el-input v-model="refund.remarks" type="textarea" :rows="3"  placeholder="请输入退款说明" class="public" clearable />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button id="refund-btn" type="primary" @click="refundSubmit('refundRuleForm')">退 款</el-button>
      </span>
    </el-dialog>
    <!--详情蒙层-->
    <el-dialog id="view-dialog" title="订单详情" :visible.sync="viewDialogVisible" v-if="detailData">
      <el-form label-position="right" label-width="30%" :model="detailData">
        <div>
          <el-form-item label="用户昵称：" v-if='detailData.member'>
            <div>{{detailData.member.name}}</div>
          </el-form-item>
          <el-form-item label="代理昵称：" v-if='detailData.agent'>
            <div>{{detailData.agent.name}}</div>
          </el-form-item>
          <el-form-item label="订单编号：">
            <div>{{detailData.sn}}</div>
          </el-form-item>
          <el-form-item label="订单状态：">
            <el-tag size="small" v-if="detailData.status==='unpaid'" type="danger">未支付</el-tag>
            <el-tag size="small" v-if="detailData.status==='success'" type="success">支付成功</el-tag>
            <el-tag size="small" v-if="detailData.status==='fail'" type="warning">支付失败</el-tag>
          </el-form-item>
          <el-form-item label="失败原因：" v-if="detailData.status==='fail'">
                <div style="color: crimson">{{detailData.failMsg}}</div>
          </el-form-item>
          <el-form-item label="充值金额：">
            <div>{{detailData.money}}</div>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="用户名称：" v-if="detailData.member">
            <div>{{detailData.member.userName}}</div>
          </el-form-item>
          <el-form-item label="代理名称：" v-if="detailData.agent">
            <div>{{detailData.agent.userName}}</div>
          </el-form-item>
          <el-form-item label="下单时间：">
            <div>{{detailData.createDate}}</div>
          </el-form-item>
          <el-form-item label="支付时间：" v-if="detailData.status==='success'">
            <div>{{detailData.successTime}}</div>
          </el-form-item>
          <el-form-item label="充值备注：">
            <div>{{detailData.remarks}}</div>
          </el-form-item>
        </div>
      </el-form>
        <span slot="footer" class="dialog-footer"/>
    </el-dialog>
  </div>
</template>

<script>
  import {Message} from 'element-ui';
  import request from "../../utils/request";
  import {parseTime} from "../../utils";

  export default {
    name: "recordOrder",
    data() {
      var checkMoney = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('退款金额不能为空'));
        }else if(!/^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/.test(value)){
          return callback(new Error('退款金额为最多保留两位小数的数字'));
        }else if(value>this.money){
          return callback(new Error('退款金额不可以大于可退款金额'));
        }else {
          callback();
        }
      };
      return {
        // 查询
        name: "",
        order: "",
        paypalOrder:'',
        agentName: '',
        status: null,
        statusList: [
          {
            value: 0,
            label: '未支付'
          },
          {
            value: 1,
            label: '支付成功'
          },
          {
            value: 2,
            label: '支付失败'
          }
        ],
        dateTimeRange: [],
        pickerOptions: {
              shortcuts: [
                  {
                      text: '今天',
                      onClick(picker) {
                          const end = new Date();
                          const start = new Date(end.getFullYear(), end.getMonth(), end.getDate(), 0, 0, 0);
                          picker.$emit('pick', [start, end]);
                      }
                  },
                  {
                      text: '昨天',
                      onClick(picker) {
                          const date = new Date();
                          date.setTime(date.getTime() - 3600 * 1000 * 24);
                          let start = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
                          let end = new Date(new Date().getFullYear(), new Date().getMonth(), date.getDate(), 23, 59, 59);
                          picker.$emit('pick', [start, end]);
                      }
                  },
                  {
                      text: '前天',
                      onClick(picker) {
                          const date = new Date();
                          date.setTime(date.getTime() - 3600 * 1000 * 24* 2);
                          let start = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
                          let end = new Date(new Date().getFullYear(), new Date().getMonth(), date.getDate(), 23, 59, 59);
                          picker.$emit('pick', [start, end]);
                      }
                  },
                  {
                      text: '本月',
                      onClick(picker) {
                          const end = new Date();
                          const start = new Date(end.getFullYear(), end.getMonth(), 1, 0, 0, 0);
                          picker.$emit('pick', [start, end]);
                      }
                  },
                  {
                      text: '上月',
                      onClick(picker) {
                          const date = new Date();
                          date.setTime(date.getTime() - 3600 * 1000 * 24 * 30);
                          let start = new Date(date.getFullYear(), date.getMonth(), 1, 0, 0, 0);
                          let end = new Date(new Date().getFullYear(), new Date().getMonth(), 1, 23, 59, 59);
                          end.setTime(end.getTime() - 3600 * 24 * 1000);
                          picker.$emit('pick', [start, end]);
                      }
                  },
                  {
                      text: '最近一周',
                      onClick(picker) {
                          const end = new Date();
                          const start = new Date();
                          start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                          picker.$emit('pick', [start, end]);
                      }
                  },
                  {
                      text: '最近一个月',
                      onClick(picker) {
                          const end = new Date();
                          const start = new Date();
                          start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                          picker.$emit('pick', [start, end]);
                      }
                  },
                  {
                      text: '最近三个月',
                      onClick(picker) {
                          const end = new Date();
                          const start = new Date();
                          start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                          picker.$emit('pick', [start, end]);
                      }
                  }
              ]
          },
        isClearable: true,
        allOrder:{},
        // 列表数据
        tableData: [],
        //订单退款
        refundDialogVisible:false,
        refund:{
          id:null,
          money:'',
          remarks:'',
        },
        money:0,
        refundRules:{
          money:[{validator: checkMoney, trigger: 'blur' }]
        },
        //详情
        viewDialogVisible: false,
        detailData: {},
        //分页
        currentPage: 1,
        pageSize: 10,
        total: 0
      }
    },
    mounted() {
        // const end = new Date();
        // const start = new Date(end.getFullYear(), end.getMonth(), end.getDate(), 0, 0, 0);
        // this.dateTimeRange = [parseTime(start), parseTime(end)];
        this.inquiryList();
    },
    methods: {
      isNotNull(value) {
        return value !== null && value !== undefined && value !== "";
      },
      //查询列表
      inquiryList() {
        let that = this;
        that.tableData = [];
        let data = {
          pageNumber: that.currentPage,
          pageSize: that.pageSize,
          filters: []
        };
        if (that.isNotNull(that.name)) { //用户昵称
          data.filters.push({
            property: "m.name",
            value: that.name,
            operator: "like"
          })
        }
        if (that.isNotNull(that.agentName)) { //代理名称
          data.filters.push({
            property: "a.name",
            value: that.agentName,
            operator: "like"
          })
        }
        if (that.isNotNull(that.order)) { //系统订单编号
          data.filters.push({
            property: "ro.sn",
            value: that.order,
            operator: "eq"
          })
        }
        if (that.isNotNull(that.paypalOrder)) { //paypal订单编号
          data.filters.push({
            property: "ro.paypal_sn",
            value: that.paypalOrder,
            operator: "eq"
          })
        }
        if (that.isNotNull(that.status)) { //订单状态
          data.filters.push({
            property: "ro.status",
            value: that.status,
            operator: "eq"
          })
        }
        if (this.isNotNull(that.dateTimeRange)) { //下单时间
          data.filters.push({
            property: "ro.create_date",
            value: that.dateTimeRange[0],
            operator: "ge"
          });
          data.filters.push({
            property: "ro.create_date",
            value: that.dateTimeRange[1],
            operator: "le"
          })
        }
        request({
          method: 'post',
          url: 'admin/recordOrder/list',
          headers: {
            'Content-Type': 'application/json;charset=UTF-8'
          },
          data: data
        }).then(function (res) {
          if (res.code === 200) {
            that.total = res.data.total;
            let arr = res.data.records;
            if (arr.length === 0) {
              that.tableData = [];
            } else {
              that.tableData = arr
            }
          }
        }).catch(function (error) {
          console.log(error);
        });
        //订单查询统计
        request({
          method: 'post',
          url: 'admin/recordOrder/list/count',
          headers: {
            'Content-Type': 'application/json;charset=UTF-8'
          },
          data: data
        }).then(function (res) {
          if (res.code === 200) {
            that.allOrder=res.data;
          }
        }).catch(function (error) {
          console.log(error);
        });
      },
      //订单退款
      dealwithRefund(index, row){
        this.refundDialogVisible=true;
        this.refund.id=row.id;
        this.money=row.money-row.refundMoney;
      },
      refundSubmit(formName){
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let that=this;
            request({
              method: 'post',
              url: 'admin/recordOrder/refund',
              params:that.refund
            }).then(function (res) {
              if(res.code===200){
                that.refundDialogVisible = false;
                Message.success("退款成功");
                that.$refs['refundRuleForm'].resetFields();
                that.refund.remarks='';
                that.inquiryList();
              }
            }).catch(function (error) {
              console.log(error);
            });
          }else {
            return false;
          }
        });
      },
      //详情
      dealwithView(index, row) {
        this.detailData = row;
        this.viewDialogVisible = true;
      },
      // 改变每页显示的数量
      handleSizeChange(val) {
        this.pageSize = val;
        this.inquiryList();
      },
      //改变当前页
      handleCurrentChange(val) {
        this.currentPage = val;
        this.inquiryList();
      }
    }
  }
</script>

<style src="../../assets/css/publicCss/publicStyle.css">

</style>
